package com.org.litepal.slice.manager;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.RoundProgressBar;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.litepal.harmony.ResourceTable;
import com.org.litepal.provider.StringItemProvider;
import org.litepal.tablemanager.Connector;
import org.litepal.util.DBUtility;

import java.util.ArrayList;
import java.util.List;

/**
 * 表列表
 */
public class TableListAbilitySlice extends AbilitySlice {
    private RoundProgressBar progressBar;

    private final ArrayList<String> mList = new ArrayList<>();
    private StringItemProvider itemProvider;
    private final EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_table_list);

        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_listTable);
        progressBar = (RoundProgressBar) findComponentById(ResourceTable.Id_pbTable);
        progressBar.setDividerLineThickness(3);
        progressBar.setIndeterminate(true);

        itemProvider = new StringItemProvider(mList, this.getContext());
        listContainer.setItemProvider(itemProvider);

        //查询所有表
        populateTables();

        listContainer.setItemClickedListener((listContainer1, component, i, l) -> {
            //点击跳转到表结构信息页面
            Intent intentStart = new Intent();
            intentStart.setParam(TableStructureAbilitySlice.TABLE_NAME, mList.get(i));
            present(new TableStructureAbilitySlice(), intentStart);
        });
    }

    /**
     * 查询所有表
     */
    private void populateTables() {
        progressBar.setVisibility(Component.VISIBLE);
        //子线程查询所有表
        new Thread(() -> {
            //查询所有表
            List<String> tables = DBUtility.findAllTableNames(Connector.getDatabase());
            for (String table : tables) {
                //忽略自动生成的3个表
                if (table.equalsIgnoreCase("Harmony_metadata")
                        || table.equalsIgnoreCase("sqlite_sequence")
                        || table.equalsIgnoreCase("table_schema")) {
                    continue;
                }
                mList.add(table);
            }
            //主线程更新列表
            handler.postTask(() -> {
                progressBar.setVisibility(Component.HIDE);
                itemProvider.notifyDataChanged();
            });
        }).start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeAllEvent();
    }
}